package org.example;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.ConstVal;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.IFileCreate;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.FileType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * @program: reject-service
 * @description:
 * @author: 施孟强
 * @create: 2021-04-16 17:01
 **/
public class MyCodeGenerator {


    public static void main(String[] args) {
        execute("libo", "mybatis-plus", "com.juzishuke.jdd.margin.biz", "", "",
                "third_deduct_202403");

    }

    public static void execute(String author, String serviceNme, String parentPackage,
            String moduleName, String tableNamePrefix, String... tableNames) {

        if (parentPackage == null || tableNames == null || tableNames.length == 0) {
            throw new MybatisPlusException("入参不能为空");
        }
        //根目录
        final String property = System.getProperty("user.dir") + "/" + serviceNme;
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbQuery(new JzMySqlQuery());
/*
        dataSourceConfig.setUrl("jdbc:mysql://pre-shop-mysql-master.juzishuke.com:3306/financep?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull");
        dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
        dataSourceConfig.setUsername("shop_rw");
        dataSourceConfig.setPassword("fxoVlSaw6Ny8Ea0M");
*/


/*

        dataSourceConfig.setUrl("jdbc:mysql://pre-shop-mysql-master.juzishuke.com:3306/financep?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull");
        dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
        dataSourceConfig.setUsername("shop_rw");
        //sandbox vou693oZGuva9H07
        dataSourceConfig.setPassword("fxoVlSaw6Ny8Ea0M");
*/
/*

       dataSourceConfig.setUrl("jdbc:mysql://rm-2ze7pj2n827y9plk5.mysql.rds.aliyuncs.com:3306/fms-sandbox?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull");
       dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
       dataSourceConfig.setUsername("core_rw_new");
       //sandbox vou693oZGuva9H07
       dataSourceConfig.setPassword("b5BObaW9Hp7nMlsV");*/

        dataSourceConfig.setUrl(
                "jdbc:mysql://lt-shop-mysql-master.juzishuke.com:3306/lt-api-accounts-bill?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull");
        dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
        dataSourceConfig.setUsername("shop_rw_new");
        //sandbox vou693oZGuva9H07
        dataSourceConfig.setPassword("vou693oZGuva9H07");

        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setOutputDir(property + "/src/main/java");
        globalConfig.setAuthor(author);
        globalConfig.setOpen(false);

        mpg.setGlobalConfig(globalConfig.setAuthor(author));
        mpg.setDataSource(dataSourceConfig);

        globalConfig.setDateType(DateType.TIME_PACK);
        globalConfig.setEntityName(null);
        globalConfig.setIdType(IdType.ASSIGN_ID);
        globalConfig.setFileOverride(true);
        globalConfig.setBaseResultMap(true);
        globalConfig.setBaseColumnList(true);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(parentPackage);
        pc.setModuleName(moduleName);
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
                if(this.getMap() == null) {
                    this.setMap(new HashMap<String, Object>());
                }
                this.getMap().put(FileType.SERVICE.name() + "_fileOverride", false);
                this.getMap().put(FileType.MAPPER.name() + "_fileOverride", false);
                this.getMap().put(FileType.SERVICE_IMPL.name() + "_fileOverride", false);
                this.getMap().put(FileType.CONTROLLER.name() + "_fileOverride", false);
                this.getMap().put(FileType.ENTITY.name() + "_fileOverride", true);
                this.getMap().put(FileType.OTHER.name() + "_fileOverride", true);
                this.getMap().put(FileType.XML.name() + "_fileOverride", true);
            }

            @Override
            public IFileCreate getFileCreate() {
                return new IFileCreate() {
                    @Override
                    public boolean isCreate(ConfigBuilder configBuilder, FileType fileType,
                            String filePath) {
                        File file = new File(filePath);
                        boolean exist = file.exists();
                        if (!exist) {
                            file.getParentFile().mkdirs();
                            return true;
                        }
                        if (configBuilder.getGlobalConfig().isFileOverride()) {
                            if (Objects.equals(configBuilder.getInjectionConfig().getMap()
                                            .getOrDefault(fileType.name() + "_fileOverride", true),
                                    false)) {
                                return false;
                            } else {
                                return true;
                            }
                        }
                        return !exist || configBuilder.getGlobalConfig().isFileOverride();
                    }
                };
            }
        };

        // 如果模板引擎是 freemarker
        // String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return property + "/src/main/resources/mapper/" + pc.getModuleName() + "/"
                        + tableInfo.getMapperName() + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        templateConfig.setController(ConstVal.TEMPLATE_CONTROLLER);
        templateConfig.setController(null);

        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setTablePrefix(tableNamePrefix);
        strategy.setEntityLombokModel(true);
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //        strategy.setSuperEntityClass(null);
        strategy.setEntityLombokModel(true);
        strategy.setLogicDeleteFieldName("dr");
        strategy.setRestControllerStyle(false);
        strategy.setInclude(tableNames);
        List<TableFill> tableFillList = new ArrayList<TableFill>();
        tableFillList.add(new TableFill("create_time", FieldFill.INSERT));
        tableFillList.add(new TableFill("update_time", FieldFill.INSERT_UPDATE));
        strategy.setTableFillList(tableFillList);
        strategy.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategy);
        mpg.execute();

    }
}
